package com.ruoyi.project.module.common.utils;

import cn.hutool.extra.pinyin.PinyinUtil;
import com.ruoyi.project.system.dict.domain.DictData;
import com.ruoyi.project.system.dict.domain.DictType;
import com.ruoyi.project.system.dict.mapper.DictDataMapper;
import com.ruoyi.project.system.dict.mapper.DictTypeMapper;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.util.*;

import static cn.hutool.core.util.CharUtil.UNDERLINE;

/**
 * 创建数据字典
 */
@RunWith(SpringRunner.class)
@SpringBootTest()
public class GenDict {

    @Autowired
    DictTypeMapper dictTypeMapper;

    @Autowired
    DictDataMapper dictDataMapper;

    public static String upperCase(String str) {
        char[] ch = str.toCharArray();
        if (ch[0] >= 'a' && ch[0] <= 'z') {
            ch[0] = (char) (ch[0] - 32);
        }
        return new String(ch);
    }

    public static String underlineToCamel(String param) {
        if (param == null || "".equals(param.trim())) {
            return "";
        }
        int len = param.length();
        StringBuilder sb = new StringBuilder(len);
        Boolean flag = false; // "_" 后转大写标志,默认字符前面没有"_"
        for (int i = 0; i < len; i++) {
            char c = param.charAt(i);
            if (c == UNDERLINE) {
                flag = true;
                continue;   //标志设置为true,跳过
            } else {
                if (flag == true) {
                    //表示当前字符前面是"_" ,当前字符转大写
                    sb.append(Character.toUpperCase(param.charAt(i)));
                    flag = false;  //重置标识
                } else {
                    sb.append(Character.toLowerCase(param.charAt(i)));
                }
            }
        }
        return sb.toString();
    }

    @Test
    public void doSave() {
        List<DictType> dictTypeList = dictTypeMapper.selectDictTypeAll();
        for (DictType dictType : dictTypeList) {
            String dictTypeStr = dictType.getDictType();
            System.out.println(dictTypeStr);
            String className = underlineToCamel(dictTypeStr);
            String ClassName = upperCase(className);

            List<DictData> dictDataList = dictDataMapper.selectDictDataByType(dictTypeStr);
            ArrayList<Object> columns = new ArrayList<>();
            for (DictData dictData : dictDataList) {
                Map<String, Object> column = new HashMap<>();
                String label = dictData.getDictLabel();
                String key = PinyinUtil.getFirstLetter(label, "").toUpperCase();
                String value = dictData.getDictValue();
                column.put("label",label);
                column.put("key",key);
                column.put("value",value);
                columns.add(column);
            }
            System.out.println(columns);
            VelocityContext context = new VelocityContext();
            context.put("dictName",dictType.getDictName());
            context.put("ClassName",ClassName);
            context.put("columns",columns);
            doRelease(context);
        }
    }


    public static String getOpsPath(String className){
        String basePath = System.getProperty("user.dir");
        String path = basePath +  "/src/main/java/com/ruoyi/project/module/common/dict/" + className + ".java";
        return path;
    }

    public static String getTemplatePath(){
        String basePath = System.getProperty("user.dir");
        String path = basePath +  "/target/classes/vm/java/dict.java.vm";
        return path;
    }

    public void doRelease(VelocityContext context){
        try {
            Properties p = initVelocityProperties();
            Velocity.init(p);
            Template template = getVelocityTemplate(getTemplatePath());

            String className = (String) context.get("ClassName");
            String ops = getOpsPath(className);
            BufferedWriter writer = getWriterStream(ops);

            template.merge(context, writer);
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public Properties initVelocityProperties() throws Exception{
        Properties p = new Properties();
        try{
            p.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, "");
            p.setProperty(Velocity.ENCODING_DEFAULT, "UTF-8");
            p.setProperty(Velocity.INPUT_ENCODING, "UTF-8");
            p.setProperty(Velocity.OUTPUT_ENCODING, "UTF-8");
        }catch(Exception e){
            e.printStackTrace();
        }
        return p;
    }

    public Template getVelocityTemplate(String filePath) throws Exception{
        Template template = new Template();
        try{
            template = Velocity.getTemplate(filePath);
        }catch(Exception e){
            e.printStackTrace();
        }
        return template;
    }

    public BufferedWriter getWriterStream(String filePath) throws Exception{
        try{
            FileOutputStream fos = new FileOutputStream(filePath);
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(fos, "UTF-8"));
            return writer;
        }catch(Exception e){
            e.printStackTrace();
        }
        return null;
    }


}
